import type {AxiosResponse, InternalAxiosRequestConfig} from "axios";
import axios from "axios";
import {useUserStoreHook} from "@/stores/modules/user";
import {ResultEnum} from "@/enums/ResultEnum";
import {TOKEN_KEY} from "@/enums/CacheEnum";
import {ElMessage, ElMessageBox} from "element-plus";


// 创建 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 50000,
    headers: {"Content-Type": "application/json;charset=utf-8"},
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const accessToken = localStorage.getItem(TOKEN_KEY);
        if (accessToken) {
            config.headers.Authorization = accessToken;
        }
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
        if (
            response.config.responseType === "blob" ||
            response.config.responseType === "arraybuffer"
        ) {
            return response;
        }
        const {code, msg} = response.data;
        if (code === ResultEnum.SUCCESS) {
            return response.data;
        }
        console.log("响应拦截器：", response.request.responseURL,code, msg)
        if (code === ResultEnum.TOKEN_INVALID) {
            ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                const userStore = useUserStoreHook();
                userStore.resetToken().then(() => {
                    location.reload();
                });
            }).catch(() => {
                // 用户点击“取消”时执行的操作，可以选择性地添加提示信息
                console.log("用户取消了重新登录");
            });
        }
        if (code.toString() === ResultEnum.ERROR) {
            ElMessage.error("系统出错");
        }
        return response.data;
    },
    async (error: any) => {
        ElMessage.error("系统出错");
        // 异常处理
        if (error.response.data) {
            const {code, msg} = error.response.data;
            ElMessage.error(msg || "系统出错");
        }
        return Promise.reject(error.message);
    }
);

// 导出 axios 实例
export default service;
